package com.budwk.app.sqfwDoc.codeGenerator.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.Asserts;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwDownRecordlogService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.result.Result;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ZY.Wang
 * @since 2023/12/22
 * <p>
 * excel通用的service
 */
@Slf4j
public abstract class SqfwTemplateExcelCommonService {

    public List<GenerateExcelUrlVO> generateExcel(List<ExcelCreateConfig> excelConfigList, String userId, List<String> sqfwIdList) {
        return generateExcelCommon(excelConfigList, userId, sqfwIdList, null);
    }

    public List<GenerateExcelUrlVO> generateExcelCommon(List<ExcelCreateConfig> excelConfigList, String userId, List<String> sqfwIdList, List<Sqfw_formSummary_new> summarys) {

        SysUserService sysUserService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user sysUser = sysUserService.fetch(userId);

        // 设置一些基础的信息
        BaseExcelParamDTO baseExcelParam = new BaseExcelParamDTO();
        baseExcelParam.setDownloadDate(new Date());
        baseExcelParam.setCreateUserId(userId)
                .setCreateUserName(sysUser.getUsername())
                .setCreateUserSigUrl(sysUser.getSignatureUrl())
                .setUnitId(sysUser.getUnitId())
                .setUnitName(sysUser.getUnitName())
                .setProvince(sysUser.getProvince())
                .setCity(sysUser.getCity())
                .setDistrict(sysUser.getDistrict())
                .setCounty(sysUser.getCounty())
                .setCommunity(sysUser.getCommunity());
        if (CollectionUtil.isNotEmpty(sqfwIdList)) {
            //自定义参数  App2.0使用
            Map<String,Object> param  = new HashMap<>();
            if(ObjectUtils.isNotEmpty(excelConfigList) &&!excelConfigList.isEmpty()){
                param = excelConfigList.get(0).getParam();
            }
            summarys = queryForSummaryData(sqfwIdList,param);
        }
        summarys = summarys == null ? Lists.newArrayList() : summarys;
        List<SqfwExcelForSummaryBO> dataList = getFieldDataList(summarys);
        customerPopularBaseExcelParam(baseExcelParam, userId, sqfwIdList);

        List<ExcelGeneratorConfig> generatorConfigList = getExcelCodeGeneratorConfig(excelConfigList, baseExcelParam);

        List<GenerateExcelUrlVO> resultList = Lists.newArrayList();
        for (ExcelGeneratorConfig generatorConfig : generatorConfigList) {
            BaseTemplateExcelGenerator generator = generatorConfig.getGenerator();
            // 2 下载台账
            SqfwExcelCreateCommonBO sqfwExcelCreateCommonBO = new SqfwExcelCreateCommonBO();
            sqfwExcelCreateCommonBO.setBaseExcelParamDTO(baseExcelParam);
            sqfwExcelCreateCommonBO.setDataList(dataList);

            ExcelCreateConfig generateConfig = new ExcelCreateConfig();
            BeanUtil.copyProperties(generatorConfig.getExcelCreateConfig(),generateConfig);
            sqfwExcelCreateCommonBO.setExcelCreateConfig(generateConfig);
            GenerateExcelUrlVO excel = generator.createExcel(sqfwExcelCreateCommonBO);
            if (excel != null) {
                ExcelCreateConfig e = generatorConfig.getExcelCreateConfig();
                if (e != null) {
                    excel.setFileIdentity(e.getFileIdentity());
                }
            }
            resultList.add(excel);
        }
        return resultList;
    }

    public List<GenerateExcelUrlVO> generateExcelForAdmin(List<ExcelCreateConfig> excelConfigList, String userId, List<String> forSummaryIdList) {

        SysUserService sysUserService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user sysUser = sysUserService.fetch(userId);

        // 设置一些基础的信息
        BaseExcelParamDTO baseExcelParam = new BaseExcelParamDTO();
        baseExcelParam.setDownloadDate(new Date());
        baseExcelParam.setCreateUserId(userId);
        baseExcelParam.setCreateUserName(sysUser.getUsername());
        baseExcelParam.setCreateUserSigUrl(sysUser.getSignatureUrl());
        baseExcelParam.setUnitId(sysUser.getUnitId());
        baseExcelParam.setUnitName(sysUser.getUnitName());
        baseExcelParam.setProvince(sysUser.getProvince());
        baseExcelParam.setCity(sysUser.getCity());
        baseExcelParam.setCounty(sysUser.getCounty());
        baseExcelParam.setCommunity(sysUser.getCommunity());
        baseExcelParam.setDistrict(sysUser.getDistrict());

        List<Sqfw_formSummary_new> formSummaryList = queryForSummaryDataForAdmin(forSummaryIdList);
        List<SqfwExcelForSummaryBO> dataList = getFieldDataList(formSummaryList);
        customerPopularBaseExcelParamForAdmin(baseExcelParam, userId, forSummaryIdList);

        List<ExcelGeneratorConfig> generatorConfigList = getExcelCodeGeneratorConfig(excelConfigList, baseExcelParam);

        List<GenerateExcelUrlVO> resultList = Lists.newArrayList();
        for (ExcelGeneratorConfig generatorConfig : generatorConfigList) {
            BaseTemplateExcelGenerator generator = generatorConfig.getGenerator();
            // 2 下载台账
            SqfwExcelCreateCommonBO sqfwExcelCreateCommonBO = new SqfwExcelCreateCommonBO();
            sqfwExcelCreateCommonBO.setBaseExcelParamDTO(baseExcelParam);
            sqfwExcelCreateCommonBO.setDataList(dataList);

            ExcelCreateConfig generateConfig = new ExcelCreateConfig();
            BeanUtil.copyProperties(generatorConfig.getExcelCreateConfig(),generateConfig);
            sqfwExcelCreateCommonBO.setExcelCreateConfig(generateConfig);

            GenerateExcelUrlVO excel = generator.createExcel(sqfwExcelCreateCommonBO);
            resultList.add(excel);
        }
        return resultList;
    }

    /**
     * 这个方法用户可以自定义重写，在这个方法中可以根据sqfwId进行查询
     *
     * @param formSummaryNewIdList 表单数据id list
     * @return 结果
     */
    protected List<Sqfw_formSummary_new> queryForSummaryDataForAdmin(List<String> formSummaryNewIdList) {
        SqfwFormsummaryNewService sqfwFormsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);

        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getId, "in", formSummaryNewIdList);
        return sqfwFormsummaryNewService.query(cnd);
    }

    /**
     * 这个方法用户可以自定义重写，在这个方法中可以根据sqfwId进行查询
     *
     * @param sqfwIdList 社区服务id list
     * @return 结果
     */
    protected List<Sqfw_formSummary_new> queryForSummaryData(List<String> sqfwIdList,Map<String,Object> param) {
        SqfwFormsummaryNewService sqfwFormsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);

        if (sqfwIdList.size() == 0) return Collections.emptyList();
        String sqfwFormSummaryType = getSqfwFormSummaryType();
        if (StringUtils.isBlank(sqfwFormSummaryType)) Asserts.fail("forSummary类型不能为空");
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getSqfwId, "in", sqfwIdList).and("type", "=", sqfwFormSummaryType);
        return sqfwFormsummaryNewService.query(cnd);
    }

    protected List<SqfwExcelForSummaryBO> getFieldDataList(List<Sqfw_formSummary_new> formSummaryList) {
        List<SqfwExcelForSummaryBO> resultList = Lists.newArrayList();
        for (Sqfw_formSummary_new sqfw_formSummary_new : formSummaryList) {

            SqfwExcelForSummaryBO forSummaryBO = new SqfwExcelForSummaryBO();
            forSummaryBO.setSqfwFormSummaryNew(sqfw_formSummary_new);

            String paramData = sqfw_formSummary_new.getParamData();
            forSummaryBO.setCustomerPdfCreateField(parseParamData(paramData));

            resultList.add(forSummaryBO);
        }
        return resultList;
    }

    /**
     * 用户自定义填充生成excel表格等的基础数据
     */
    protected abstract void customerPopularBaseExcelParam(BaseExcelParamDTO baseExcelParam, String userId, List<String> sqfwIdList);

    protected abstract void customerPopularBaseExcelParamForAdmin(BaseExcelParamDTO baseExcelParam, String userId, List<String> formSummaryNewIdList);

    /**
     * 选择使用什么代码生成器
     *
     * @return 结果
     */
    protected abstract List<ExcelGeneratorConfig> getExcelCodeGeneratorConfig(List<ExcelCreateConfig> excelConfigList, BaseExcelParamDTO baseExcelParam);

    /**
     * 提供了一个方法将数据字符串转为对象
     *
     * @param paramDataStr 参数字符串
     * @return 结果
     */
    protected abstract AbstractCustomerPdfCreateField parseParamData(String paramDataStr);

    /**
     * 获取类型，改类型用于查询sqfw_form_summary_new这种表的数据
     *
     * @return 结果
     */
    protected abstract String getSqfwFormSummaryType();
}
